
package com.jf.cloud.user.listener;

import com.jf.cloud.common.util.Json;
import com.jf.cloud.user.model.UserBalanceLog;
import com.jf.cloud.user.service.UserBalanceLogService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;


/**
 * 确认收货事务监听
 * @author zz
 * @date 2021/1/7
 */
@Component
@RocketMQTransactionListener(rocketMQTemplateBeanName = "balancePayTemplate",maximumPoolSize = 20)
public class BalancePayTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private UserBalanceLogService userBalanceLogService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object userBalanceLog) {
        Long payId = Json.parseObject((byte[])msg.getPayload(), Long.class);
        // 扣减余额，并将余额记录的支付状态变为已支付
        userBalanceLogService.updateToOrderPaySuccess(payId,(UserBalanceLog) userBalanceLog);
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        Long payId = Json.parseObject((byte[])msg.getPayload(), Long.class);
        // 查询支付状态
        UserBalanceLog userBalanceLog = userBalanceLogService.getByPayId(payId);
        if (!Objects.equals(userBalanceLog.getIsPayed(), 0)) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
